# -*- mode: python -*-
###
#
# (c) 2000-2007 Wijnand Modderman <wijnand at tehmaze dot com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###

__revision__ = '$Hg:$'

# system imports
import types

# DDB imports
from ddb.tools import syntax
from ddb.register import register
from ddb.access import access

# DDB exports
EXPORT=['Register']

class Register:
    @access('n', 'n')
    def register(self, event):
        """<[set]|[get]|[show]> <<[section]> <[key]> [value]>

        Get or set information in the register for the specified section. The value in the set action
        is a python-style int, float, string or list. For more information about how to format these
        types, please refer to http://docs.python.org/lib/types.html."""
        action = ''
        if event.args:
            action = event.args.split()[0]
        if len(event.args.split()) not in [3, 4] and not hasattr(self, '_register_%s' % action):
            return event.reply(syntax())
        call = getattr(self, '_register_%s' % action)
        call(event)

    def _register_get(self, event):
        """get <[section]> <[key]> <[value]>"""
        try:
            _, module, key = event.args.split()
        except ValueError:
            return event.reply(syntax().replace('_register_get', 'register'))
        if not register.sectionExists(module):
            return event.reply('No such section exists in the registry')
        value = register.get(module, key)
        if value and len(value) == 1:
            value = value[0] # because the registry only stores lists
        event.reply('%s(%s) = %s' % (module, key, str(value)))

    def _register_set(self, event):
        """get <[section]> <[key]>"""
        try:
            _, module, key, value = event.args.split(' ', 3)
        except ValueError:
            return event.reply(syntax().replace('_register_set', 'register'))
        if not register.sectionExists(module):
            register.sectionAdd(module)
        oldValue = register.get(module, key)
        if oldValue:
            vtype = type(oldValue[0])
        # some evil eval jail here
        _jail = {'__builtins__': types.ModuleType('__builtins__')}
        try:
            newValue = [eval(value, _jail, _jail)]
        except Exception, e:
            return event.reply('Syntax error: %s' % str(e))
        if oldValue and not vtype == type(newValue[0]):
            event.reply('Warning: assignment of variable is not the same type!')
            event.reply('Old value: %s' % str(oldValue))
        event.reply('New value: %s' % str(newValue))
        register.set(module, key, newValue)

    def _register_show(self, event):
        # we only want the plain modules, not all per-command settings
        sections = [x for x in register.sections() if not ':' in x]
        sections.sort()
        if sections:
            event.reply('registry sections: %s' % ', '.join(sections))
        else:
            event.reply('no sections found in the registry')

# vim:ts=4:sw=4:et:
